// pages/create/create.js
var util = require("../../utils/util.js")
var api = require("../../utils/api.js")
var QQMapWX = require('../../utils/qqmap/qqmap-wx-jssdk.js');
const uploadImage = require('../../utils/oss/uploadAliyun.js');
let app = getApp();
var qqmapsdk;
let a = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    length: 0,
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '创建团队', //导航栏 中间的标题
    },
    // 此页面 页面内容距最顶部的距离
    height: app.globalData.height * 2 + 20,
    source: '',
    text: '',
    latitude: '',
    longitude: '',
    username: '',
    address: '',
    city: '',
    province: '',
    pic: '',
    userInfo: {
      content: 1
    },
    pid: 0,
  },
  //获取输入的字数
  userInput: function(e) {
    var that = this
    that.setData({
      length: e.detail.value.length,
      text: e.detail.value
    })
  },
  nameinput: function(e) {
    var that = this
    that.setData({
      username: e.detail.value
    })
  },
  chooseLocation: function(e) {
    a = true
    var that = this
    wx.chooseLocation({
      success: function(res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          address: res.address
        })
        that.getLocal(res.latitude, res.longitude)
      },

    })

  },
  uploadimg: function() {
    var that = this;
    wx.chooseImage({ //从本地相册选择图片或使用相机拍照
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        //console.log(res)
        //前台显示
        that.setData({
          source: res.tempFilePaths
        })
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths

        let data = new Date();
        let url = util.formatDataYMD(data) + "/" + tempFilePaths[0].replace('wxfile://', '')
        that.setData({
          pic: app.globalData.ossUrl + url
        })
        //filePath为要上传的本地文件的路径
        //第二个参数为oss目录
        uploadImage(tempFilePaths[0], util.formatDataYMD(data) + "/",
          function (res) {
            console.log("上传成功")
            //todo 做任何你想做的事
          }, function (res) {
            console.log("上传失败")
            //todo 做任何你想做的事
          }
        )
        // wx.uploadFile({
        //   url: app.u.H + app.u.river.UPLOADIMG,
        //   filePath: tempFilePaths[0],
        //   name: 'file',
        //   success: function(res) {
        //     //打印
        //     that.setData({
        //       pic: res.data
        //     })
        //   }
        // })
      }
    })
  },
  getbot: function() {
    var that = this
    if (that.data.pic == "") {
      api.showError('群头像不能为空')
      return;
    }
    if (that.data.username.length == "") {
      api.showError('群名称不能为空')
      return;
    }
    if (that.data.username.length == "") {
      api.showError('群名字不能为空')
      return;
    }
    if (that.data.username.length > 0 && that.data.username.length > 10) {
      api.showError('最多十个字')
      return;
    }
    if (that.data.address == "") {
      api.showError('地址不能为空')
      return;
    }
    if (that.data.text.length == "") {
      api.showError('群介绍不能为空')
      return;
    }
    console.log(that.data.latitude)
    console.log(that.data.longitude)
    //查询数据
    var data = {
      name: that.data.username,
      province: that.data.province,
      pic: that.data.pic,
      city: that.data.city,
      intro: that.data.text,
      address: that.data.address,
      account_id: wx.getStorageSync('userinfo').id,
      longitude: that.data.longitude,
      latitude: that.data.latitude,
      pid: that.data.pid,
    }
    var url = app.u.H + app.u.river.CREATEGROUP
    api.requestUrl(data, url).then(res => {
      if (res.code == 200) {
        wx.setStorageSync('userinfo', res.data)
        setTimeout(function() {
          api.showError(res.msg)
          wx.switchTab({
            url: '../group/group'
          })
        }, 1000)
      } else {
        // wx.setStorageSync('userInfo', that.data.userInfo)
        // setTimeout(function () {
        // 	api.showError(res.msg)
        // 	wx.switchTab({
        // 		url: '../group/group'
        // 	})
        // }, 1000)
        api.showError(res.msg)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    if (options.pid == undefined) {

    } else {
      that.setData({
        pid: options.pid
      })
    }

  },
  getUserLocation: function() {
    let vm = this;
    wx.getSetting({
      success: (res) => {
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function(res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function(dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        } else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  },
  // 微信获得经纬度
  getLocation: function() {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        vm.getLocal(latitude, longitude)
      },
      fail: function(res) {}
    })
  },

  getLocal: function(latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function(res) {
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        vm.setData({
          province: province,
          city: city
        })
      },
      fail: function(res) {},
      complete: function(res) {
        // console.log(res);
      }
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (a) {
      return
    }
    var that = this
    qqmapsdk = new QQMapWX({
      key: 'TTWBZ-6L56U-W55V3-BJZJ6-KGGYF-O2BRB'
    })
    wx.getLocation({
      type: 'gcj02',
      success: function(res) {
        that.getUserLocation()
        that.getLocal(res.laitude, res.longitude)
      },
    })
  },
})